from django.db import models
from json import loads
# from django.utils.timezone import now
# import time as p_time
import datetime


# Create your models here.
# 数据表，存放传感器数据。
# |id | time | temperature | humidity | co2 | dust |
# --------------------------------------------------
# |   |      |             |          |     |       |
class SensorData(models.Model):

    # 传感器数据更新的时间列
    time = models.DateTimeField()

    # 温度数据列
    temperature = models.FloatField()

    # 湿度数据列
    humidity = models.FloatField()

    # co2数据列
    co2 = models.FloatField()

    # 粉尘浓度数据列
    dust = models.FloatField()

    class Meta:
        ordering = ("time",)
        get_latest_by = "time"


def db_add_record(rec=''):
    # 把得到的str转换成json对象，注意，这个地方可能会产生解析错误
    try:
        jsobj = loads(rec)

        # 向数据库中添加记录了。
        # 传送的数据格式：{"tmp": 12.3, "hum": 22.5, "dust": 34522, "co2": 23333}
        SensorData.objects.create(time=datetime.datetime.now(),
                                  temperature=jsobj['tmp'],
                                  humidity=jsobj['hum'],
                                  co2=jsobj['co2'],
                                  dust=jsobj['dust'])
        # 尝试把得到的json对象返回回去
        print(jsobj)
        return jsobj
    except SyntaxError as serr:
        return str(serr)
    except Exception as err:
        return 'Exception:' + str(err)

# 删除所有记录
def db_remove_all():
    SensorData.objects.all().delete()

